<template>
  <div style="margin-top: 50px">
    <el-form :model="form" ref="productAttrForm" label-width="120px" class="form-inner-container" size="small">
      <el-form-item label="属性类型：">
        <el-select v-model="form.productAttributeCategoryId" placeholder="请选择属性类型" @change="handleProductAttrChange">
          <el-option v-for="item in productAttributeCategoryOptions" :key="item.id" :label="item.name" :value="item.id"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品规格：">
        <el-card v-if="form.productAttributeCategoryId" shadow="never" class="cardBg">
          <div v-for="(productAttr, i) in selectProductAttr" :key="i">
            {{ productAttr.name }}：
            <el-checkbox-group v-model="productAttr.values">
              <template v-if="productAttr.handAddStatus === 0">
                <el-checkbox v-for="item in productAttr.selectOptions" :label="item" :key="item"></el-checkbox>
              </template>
              <template v-else>
                <el-tag
                  v-for="(item, index) in [...productAttr.selectOptions, ...productAttr.options]"
                  :key="item"
                  closable
                  @close="handleRemoveProductAttrValue(productAttr, index)"
                >
                  <el-checkbox :key="item" :label="item"></el-checkbox>
                </el-tag>
              </template>
            </el-checkbox-group>
            <div v-if="productAttr.handAddStatus !== 0">
              <el-input v-model="addProductAttrValue" style="width: 160px; margin-left: 10px" clearable></el-input>
              <el-button @click="handleAddProductAttrValue(productAttr)">增加</el-button>
            </div>
          </div>
        </el-card>
        <el-table style="width: 100%; margin-top: 20px" :data="form.skuStockList" border>
          <el-table-column v-for="(item, index) in selectProductAttr" :label="item.name" :key="item.id" align="center">
            <template #default="scope">
              {{ getProductSkuSp(scope.row, index) }}
            </template>
          </el-table-column>
          <el-table-column label="销售价格" width="100" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="促销价格" width="100" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.promotionPrice"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="商品库存" width="80" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.stock"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="库存预警值" width="80" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.lowStock"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="SKU编号" width="160" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.skuCode"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template #default="scope">
              <el-button link @click="handleRemoveProductSku(scope.$index)">删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" style="margin-top: 20px" @click="handleRefreshProductSkuList">刷新列表 </el-button>
        <el-button type="primary" style="margin-top: 20px" @click="handleSyncProductSkuPrice">同步价格 </el-button>
        <el-button type="primary" style="margin-top: 20px" @click="handleSyncProductSkuStock">同步库存 </el-button>
      </el-form-item>
      <el-form-item label="属性图片：" v-if="hasAttrPic">
        <el-card shadow="never" class="cardBg">
          <div v-for="(item, index) in selectProductAttrPics" :key="index">
            <span>{{ item.name }}:</span>
            <!-- <single-upload v-model="item.pic" style="width: 300px; display: inline-block; margin-left: 10px"></single-upload> -->
          </div>
        </el-card>
      </el-form-item>
      <div>商品参数：</div>
      <el-form-item v-for="(item, index) in selectProductParam" :key="index" :label="item.name">
        <el-select v-if="item.inputType === 1" v-model="item.value">
          <el-option v-for="i in item.selectOptions" :key="i" :label="i" :value="i"> </el-option>
        </el-select>
        <el-input v-else v-model="item.value"></el-input>
      </el-form-item>
      <el-form-item label="商品相册：">
        <!-- <multi-upload v-model="selectProductPics"></multi-upload> -->
      </el-form-item>
      <el-form-item label="商品详情：">
        <el-tabs v-model="activeHtmlName" type="card">
          <el-tab-pane label="电脑端详情" name="pc">
            <!-- <tinymce :width="595" :height="300" v-model="form.detailHtml"></tinymce> -->
          </el-tab-pane>
          <el-tab-pane label="移动端详情" name="mobile">
            <!-- <tinymce :width="595" :height="300" v-model="form.detailMobileHtml"></tinymce> -->
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button size="small" @click="handlePrev">上一步</el-button>
        <el-button type="primary" size="small" @click="handleNext">下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { fetchList as fetchProductAttrCateList } from '@/api/productAttrCate'
import { fetchList as fetchProductAttrList } from '@/api/productAttr'
// import SingleUpload from '@/components/Upload/singleUpload.vue'
// import MultiUpload from '@/components/Upload/multiUpload.vue'
// import Tinymce from '@/components/Tinymce/index.vue'
import type { ProductAttrCate } from '@/models/productAttrCate'
import type { ProductAttr } from '@/models/productAttr'
import type { ProductDetail } from '@/models/product'

interface ProductAttrs extends ProductAttr {
  options: string[]
  values: string[]
  selectOptions: string[]
}
defineOptions({ name: 'ProductAttrDetail' })

const emit = defineEmits(['nextStep', 'prevStep', 'update:modelValue'])
const route = useRoute()
const props = withDefaults(defineProps<{ modelValue: ProductDetail; isEdit: boolean }>(), {
  modelValue: () => ({}),
  isEdit: false,
})
const form = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit('update:modelValue', val)
  },
})

const hasEditCreated = ref(false)
const productAttributeCategoryOptions = ref<ProductAttrCate[]>([])
const selectProductAttr = ref<ProductAttrs[]>([])
const selectProductParam = ref<ProductAttrs[]>([])
const selectProductAttrPics = ref<{ name: string; pic: string }[]>([])
const addProductAttrValue = ref('')
const activeHtmlName = ref('pc')
const hasAttrPic = computed(() => selectProductAttrPics.value.length >= 1)
const selectProductPics = computed({
  get: function () {
    const pics = form.value.albumPics?.split(',') || []
    form.value.pic && pics.unshift(form.value.pic)
    return pics
  },
  set: function (newValue) {
    if (newValue?.length === 0) {
      form.value.pic = ''
      form.value.albumPics = ''
    } else {
      form.value.pic = newValue[0]
      form.value.albumPics = newValue.join(',')
    }
  },
})
watch(
  () => form.value.id,
  (val) => {
    if (val === undefined || val == null || val === 0) {
      return
    }
    if (hasEditCreated.value || route.query.id == null || route.query.id === '') {
      return
    }
    handleEditCreated()
  }
)
getProductAttrCateList()
function handleEditCreated() {
  //根据商品属性分类id获取属性和参数
  if (form.value.productAttributeCategoryId != null) {
    handleProductAttrChange(form.value.productAttributeCategoryId)
  }
  hasEditCreated.value = true
}
async function getProductAttrCateList() {
  const param = { pageNum: 1, pageSize: 100 }
  const response = await fetchProductAttrCateList(param)
  productAttributeCategoryOptions.value = response.data.data.list
}
async function getProductAttrList(type: number, cid: number) {
  const param = { pageNum: 1, pageSize: 100, type: type }
  const response = await fetchProductAttrList(cid, param)
  const list = response.data.data.list
  if (type === 0) {
    selectProductAttr.value = list.map((item, i) => {
      const options = form.value.productAttributeValueList?.find((i) => i.productAttributeId === item.id)?.value?.split(',') || []
      return { ...item, options, selectOptions: item.inputList ? item.inputList?.split(',') : [], values: getEditAttrValues(item.name) }
    })
    route.query.id && refreshProductAttrPics()
  } else {
    selectProductParam.value = list.map((item) => {
      return { ...item, selectOptions: item.inputList ? item.inputList?.split(',') : [], value: getEditParamValue(item.id) }
    })
  }
}
//获取选中的属性值
function getEditAttrValues(key: number): string[] {
  const values = new Set<string>()
  form.value.skuStockList?.forEach((item: any) => {
    const spData = item.spData
    const item1 = spData.find((item) => item.key === key)
    item1 && values.add(item1.value)
  })
  return Array.from(values)
}
//获取属性的值
function getEditParamValue(id: number) {
  return form.value.productAttributeValueList?.find((item) => item.productAttributeId === id)?.value
}
function handleProductAttrChange(value: number) {
  getProductAttrList(0, value)
  getProductAttrList(1, value)
}
function handleAddProductAttrValue(productAttr: ProductAttrs) {
  console.log(productAttr)
  productAttr.options ??= []
  if (addProductAttrValue.value == null || addProductAttrValue.value == '') {
    ElMessage.warning('属性值不能为空')
    return
  }
  if (productAttr.options.indexOf(addProductAttrValue.value) !== -1) {
    ElMessage.warning('属性值不能重复')
    return
  }
  productAttr.options.push(addProductAttrValue.value)
  addProductAttrValue.value = ''
  const productAttributeValue = form.value.productAttributeValueList?.find((i) => i.productAttributeId === productAttr.id)
  if (productAttributeValue) {
    productAttributeValue.value = productAttr.options.join(',')
  } else {
    form.value.productAttributeValueList?.push({
      productAttributeId: productAttr.id,
      value: productAttr.options.join(','),
    })
  }
}
function handleRemoveProductAttrValue(productAttr: ProductAttrs, index: number) {
  productAttr.options.splice(index, 1)
}
function getProductSkuSp(row: ProductAttrs, index: number) {
  return index < row.spData?.length ? row.spData[index].value : null
}
async function handleRefreshProductSkuList() {
  await ElMessageBox.confirm('刷新列表将导致sku信息重新生成，是否要刷新', '提示', { type: 'warning' })
  refreshProductAttrPics()
  refreshProductSkuList()
}
async function handleSyncProductSkuPrice() {
  await ElMessageBox.confirm('将同步第一个sku的价格到所有sku,是否继续', '提示', { type: 'warning' })
  if (form.value.skuStockList?.length) {
    let price = form.value.skuStockList[0].price
    form.value.skuStockList.forEach((item: any) => {
      item.price = price
    })
  }
}
async function handleSyncProductSkuStock() {
  await ElMessageBox.confirm('将同步第一个sku的库存到所有sku,是否继续', '提示', { type: 'warning' })
  if (form.value.skuStockList?.length) {
    let stock = form.value.skuStockList[0].stock
    let lowStock = form.value.skuStockList[0].lowStock
    form.value.skuStockList.forEach((item: any) => {
      item.stock = stock
      item.lowStock = lowStock
    })
  }
}
function refreshProductSkuList() {
  const list = []
  const lengths = selectProductAttr.value.map((item) => item.values.length)
  const length = lengths.reduce((p, c) => p * c, 1)
  for (let i = 0; i < length; i++) {
    const spData = []
    for (let j = 0; j < selectProductAttr.value.length; j++) {
      const index = Math.floor(i / lengths[j]) % lengths[j]
      spData.push({ key: selectProductAttr.value[j].name, value: selectProductAttr.value[j].values[index] })
    }
    list.push({ spData })
  }
  form.value.skuStockList = list
}
function refreshProductAttrPics() {
  selectProductAttrPics.value = []
  if (selectProductAttr.value.length >= 1) {
    selectProductAttrPics.value = selectProductAttr.value[0].values.map((item) => ({ name: item, pic: getProductSkuPic(item) }))
  }
}
//获取商品相关属性的图片
function getProductSkuPic(name: string) {
  return form.value.skuStockList?.find((item) => item.spData[0].value === name)?.pic
}
//合并商品属性
function mergeProductAttrValue() {
  form.value.productAttributeValueList = []
  selectProductAttr.value.forEach((item) => {
    if (item.handAddStatus === 1 && item.options?.length) {
      form.value.productAttributeValueList?.push({
        productAttributeId: item.id,
        value: item.options.join(','),
      })
    }
  })
  selectProductParam.value.forEach((item) => {
    form.value.productAttributeValueList?.push({
      productAttributeId: item.id,
      value: item.value,
    })
  })
}
//合并商品属性图片
function mergeProductAttrPics() {
  form.value.skuStockList?.forEach((item) => {
    const spData = item.spData[0]?.value
    const item1 = selectProductAttrPics.value.find((i) => i.name === spData)
    item1 && (item.pic = item1.pic)
  })
}

function handleRemoveProductSku(index: number) {
  let list = form.value?.skuStockList
  list?.length === 1 ? list.pop() : list?.splice(index, 1)
}
function handlePrev() {
  emit('prevStep')
}
function handleNext() {
  mergeProductAttrValue()
  mergeProductAttrPics()
  emit('nextStep')
}
</script>

<style scoped>
.littleMarginLeft {
  margin-left: 10px;
}

.littleMarginTop {
  margin-top: 10px;
}

.paramInput {
  width: 250px;
}

.paramInputLabel {
  display: inline-block;
  width: 100px;
  text-align: right;
  padding-right: 10px;
}

.cardBg {
  background: #f8f9fc;
}
</style>
